package cn.ljlao.mall.product.goods.dataSource.controller;

import cn.ljlao.common.utils.R;
import cn.ljlao.mall.product.goods.dataSource.dto.DataSourceDTO;
import cn.ljlao.mall.product.goods.dataSource.service.ApiDataSourceService;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author liuzhen
 * @Description: 数据源动态添加 删除 查询 控制器
 * @date 2022/1/6 11:34
 */
@RestController
@RequestMapping("/datasource")
public class ApiDataSourceController {

	@Autowired
	private ApiDataSourceService apiDataSourceService;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 添加数据源
	 * @param dto
	 * @return
	 */
	@PostMapping("/add")
	public R add(@Valid @RequestBody DataSourceDTO dto){
		dto.setUrl(dto.getUrl().replace("&amp;", "&"));
		return R.ok().put("data",apiDataSourceService.add(dto));
	}

	/**
	 * 查询当前所有数据源
	 * @return
	 */
	@GetMapping("/list")
	public R list(){
		return R.ok().put("data",apiDataSourceService.now());
	}

	/**
	 * 移除数据源
	 * @param name
	 * @return
	 */
	@GetMapping("/remove")
	public R list(String name){
		return R.ok().put("data",apiDataSourceService.remove(name));
	}


	/**
	 * 测试手动切换数据源
	 * @return
	 */
	@GetMapping("/test")
	public R test(){
		DynamicDataSourceContextHolder.push("test");//手动切换
		return R.ok().put("data",jdbcTemplate.queryForList("select  * from databasesource"));
	}



}
